import classNames from 'classnames';
import { useEffect, useMemo, useState } from 'react';
import { useForm, useWatch } from 'react-hook-form';
import { Trans, useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import { useLocation, useNavigate } from 'react-router-dom';
import Alert from 'src/component/Alert';
import BackButton from 'src/component/BackButton';
import Button from 'src/component/Button';
import Form from 'src/component/Form';
import FormDatetimePicker from 'src/component/FormDatetimePicker';
import FormNumberInput from 'src/component/FormNumberInput';
import FormSelect from 'src/component/FormSelect';
import SelectOption from 'src/component/SelectOption';
import { Severity } from 'src/constant/Notification';
import { Page } from 'src/constant/Page';
// import { BankAccount } from 'src/model/Bank';
// import { TradingForm } from 'src/model/Form';
import { RootState } from 'src/redux/store';
import { openSnackbar } from 'src/redux/uiSlice';
// import { initTrading } from 'src/service/orderService';
import { getMyBank } from "src/service/userService"
import { getUserInfo } from 'src/service/userService'
import { bn, bnFixed, bnFormat } from 'src/util/bigNumber';
import PaymentMethodsList from './component/PaymentMethodsList';
import style from './Trading.module.scss';

type BankAccount = any
type TradingForm = any

const Trading = () => {
  const { t } = useTranslation();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const location = useLocation();
  const stateTradingForm = location.state as TradingForm | null;
  const methods = useForm<TradingForm>({
    defaultValues: stateTradingForm
      ? {
        ...stateTradingForm,
      }
      : undefined,
  });
  const token = localStorage.getItem("token")
  const uMail = localStorage.getItem("uMail")
  const { crypto, fiat } = useSelector((rootState: RootState) => rootState.coin);
  const { baseDataInfo } = useSelector((rootState: RootState) => rootState.basedata);
  // const { accountInfo } = useSelector((rootState: RootState) => rootState.auth);
  const [accountInfo, setAccountInfo] = useState<any>()
  const [shuaxin, setShuaxin] = useState<boolean>(false)
  // const [baseDataInfo?.FScckj, setExchangeRate] = useState<string>();
  const [bankAccount, setBankAccount] = useState<BankAccount[]>();
  const [balance, setBalance] = useState<number>();
  const [defaultCoin, setDefaultCoin] = useState<string>();
  const [defaultFiat, setDefaultFiat] = useState<string>();
  const [coinDecimal, setCoinDecimal] = useState<number>(0);
  const [fiatDecimal, setFiatDecimal] = useState<number>(0);
  const [fiatPriceDecimal, setFiatPriceDecimal] = useState<number>(0);
  const [minOrderAmount, setMinOrderAmount] = useState<string | null>();
  const [maxOrderAmount, setMaxOrderAmount] = useState<string | null>();
  const [minOrderTotal, setMinOrderTotal] = useState<string | null>();
  const [maxOrderTotal, setMaxOrderTotal] = useState<string | null>();
  const formData = useWatch({ control: methods.control });
  const bankAccountId = useMemo(
    () =>
      (bankAccount?.findIndex((value) => value.FBZh === formData.bankAccountId) ?? -1) >= 0
        ? formData.bankAccountId
        : undefined,
    [bankAccount, formData.bankAccountId],
  );
  const amountInputHint = useMemo(() => {
    const isDataReady = formData.base !== undefined && balance !== undefined;

    if (!isDataReady) return '';
    let res = `${"可用"} ${bnFormat(balance)} ${formData.base?.toUpperCase()}`;

    if (minOrderAmount && maxOrderAmount)
      res += `\n${"系统限额"} ${bnFormat(
        minOrderAmount,
      )} ${formData.base?.toUpperCase()} - ${bnFormat(
        maxOrderAmount,
      )} ${formData.base?.toUpperCase()}`;
    else if (minOrderAmount && maxOrderAmount === null)
      res += `\n${"系统限额"} ${bnFormat(
        minOrderAmount,
      )} ${formData.base?.toUpperCase()} -`;
    else if (minOrderAmount === null && maxOrderAmount)
      res += `\n${"系统限额"} 0 - ${bnFormat(
        maxOrderAmount,
      )} ${formData.base?.toUpperCase()}`;

    return res;
  }, [balance, formData.base, t]);

  useEffect(() => {
    // console.log('开启定时器')
    const timer = setInterval(() => {
      // console.log('进入定时器')
      // 注:在setCount中使用箭头函数是最好方式之一,只有一个timer生成
      const userData = {
        token: token,
        uMail: uMail
      }
      getUserInfo(userData).then(res => {
        if (res.success) {
          // let arr = {
          //   FAddtime: "2023-03-13T12:40:31.13",
          //   FCoin: 1000,
          //   FDel: 0,
          //   FGoogle: "停用",
          //   FID: "ef525747-d929-4516-bf84-21713ee8d7fb",
          //   FMail: "xiaoganguge@gmail.com",
          //   FMobile: "17635641356",
          //   FParentID: "",
          //   FPwd: "7c/6YRutHcsjO35bwMSl+FWcLm+kqFjVZ2+lfA7pPuI55MVDjONaVcQVyDoqg7s8QR/vV1Xd2reivO8O78DYMjPwSssQqzkEsWogJAkM6hRtvg2N0vf+V4nd4vofREkx5G9VHkE43NcUS+Pokrx9pdxn3fQjm5j4xD6Amoe46F4=",
          //   FState: "正常",
          //   FTicket: "5bc9905a-c7b7-4842-841c-20b84d87044f",
          //   FTrcAddres: "aaaaaaaaaa",
          //   FUserName: "g",
          //   FYjCode: "E4KXV",
          //   FdCoin: 1000,
          // }
          setAccountInfo(res.list[0])
        }
      })
    }, 5000)
    return () => {
      // console.log('清除定时器')
      clearInterval(timer)
    }
  }, [shuaxin]) //如果设置count依赖,会有多个timer生成,销毁

  useEffect(() => {
    const userData = {
      token: token,
      uMail: uMail
    }
    getUserInfo(userData).then(res => {
      if (res.success) {
        setAccountInfo(res.list[0])
        setShuaxin(true)
      }
    })
  }, [])

  useEffect(() => {
    if (!crypto[0] || !fiat[0]) return;

    setDefaultCoin(crypto[0].id);
    setDefaultFiat(fiat[0].id);
    setBalance(accountInfo?.FCoin);
  }, [crypto, fiat, accountInfo?.FCoin]);

  useEffect(() => {
    if (!formData.base || !formData.quote || !accountInfo?.FID) return;
    getMyBank({
      FUserID: accountInfo?.FID,
      token: token,
    }).then(res => {
      if (res.message) {
        setBankAccount(res.list)
      } else {
        dispatch(openSnackbar({ message: res.message, severity: 'alert' }))
      }
    }).catch(e => {
      dispatch(openSnackbar({ message: e, severity: 'alert' }))
    })
    // initTrading(formData.base, formData.quote)
    //   .then(([resRate, resBankAccount, resBalance]) => {
    //     setExchangeRate(resRate.price);
    //     setBankAccount(resBankAccount);
    //     setBalance(resBalance.free);
    //   })
    //   .catch((e) => dispatch(openSnackbar({ message: e, severity: 'alert' })));
  }, [formData.base, formData.quote, accountInfo?.FID]);

  useEffect(() => {
    if (!formData.base) return;

    setCoinDecimal(crypto.find((v) => v.id === formData.base)?.decimal ?? 0);
    setMinOrderAmount(crypto.find((v) => v.id === formData.base)?.minOrderAmount);
    setMaxOrderAmount(crypto.find((v) => v.id === formData.base)?.maxOrderAmount);
  }, [formData.base, crypto]);

  useEffect(() => {
    if (!formData.quote) return;
    setFiatDecimal(fiat.find((v) => v.id === formData.quote)?.decimal ?? 0);

    setFiatPriceDecimal(fiat.find((v) => v.id === formData.quote)?.priceDecimal ?? 0);
    setMinOrderTotal(fiat.find((v) => v.id === formData.quote)?.minOrderTotal);
    setMaxOrderTotal(fiat.find((v) => v.id === formData.quote)?.maxOrderTotal);
  }, [formData.quote, fiat]);

  useEffect(() => {
    const { price, amount, minTotal, maxTotal } = methods.getValues();
    const diff = bn(price)
      .minus(baseDataInfo?.FScckj ?? '')
      .div(baseDataInfo?.FScckj ?? '')
      .abs();
    if (price && diff.gt(0.2)) methods.setError('price', { message: "与市场价格相差 20% 以上" });
    else methods.clearErrors('price');

    if (bn(amount).gt(balance ?? ''))
      methods.setError('amount', { message: "可用余额不足" });
    else if (minOrderAmount && bn(amount).lt(minOrderAmount))
      methods.setError('amount', { message: "小于最低出售量" });
    else if (maxOrderAmount && bn(amount).gt(maxOrderAmount))
      methods.setError('amount', { message: "小于最高出售量" });
    else methods.clearErrors('amount');

    if (bn(price).times(amount).lt(minTotal))
      methods.setError('minTotal', { message: "超过广告总金额" });
    else if (minOrderTotal && bn(minTotal).lt(minOrderTotal))
      methods.setError('minTotal', { message: "低于单笔收款下限" });
    else methods.clearErrors('minTotal');

    if (bn(minTotal).gt(maxTotal))
      methods.setError('maxTotal', { message: "小于最小单笔限额" });
    else if (maxOrderTotal && bn(maxTotal).gt(maxOrderTotal))
      methods.setError('maxTotal', { message: "高于单笔收款上限" });
    else methods.clearErrors('maxTotal');
  }, [formData]);


  const onPreview = (data: TradingForm) => {
    navigate(Page.TradingConfirm, {
      state: {
        ...data,
        coin: accountInfo?.FCoin,
        bankAccount: bankAccount?.find((v) => v.FBZh === data.bankAccountId),
      },
    });
  };

  return (
    <div>
      <BackButton />
      <div className={style.heading}>
        发布广告
        <div className={style.buttons}>
          <Button appearance="text" onClick={() => navigate(Page.Trade, { replace: true })}>
            所有广告
          </Button>
          <Button appearance="text" onClick={() => navigate(Page.MyTrade, { replace: true })}>
            我的广告
          </Button>
        </div>
      </div>
      {crypto.length !== 0 && fiat.length !== 0 && defaultCoin && defaultFiat && (
        <Form methods={methods} onSubmit={onPreview}>
          <div className={style.adTypeBlock}>
            <div className={classNames(style.staticItem)}>
              <span className={style.label}>交易类型</span>
              <span className={style.value}>出售</span>
            </div>
            <div className={style.itemMargin}>
              <FormSelect
                name="base"
                label="商品"
                defaultValue={defaultCoin}
                asterisked
              >
                {crypto.map((value) => (
                  <SelectOption key={value.id} value={value.id}>
                    {value.id.toUpperCase()}
                  </SelectOption>
                ))}
              </FormSelect>
            </div>
            <div className={style.itemMargin}>
              <FormSelect
                name="quote"
                label="交易法币"
                defaultValue={defaultFiat}
                asterisked
              >
                {fiat.map((v) => (
                  <SelectOption key={v.id} value={v.id}>
                    {v.id.toUpperCase()}
                  </SelectOption>
                ))}
              </FormSelect>
            </div>
          </div>
          <div className={style.adTypeBlockDivider} />
          <div className={style.adAmountPriceBlock}>
            <div className={style.row}>
              <div className={classNames(style.input)}>
                <FormNumberInput
                  name="price"
                  label="单价"
                  decimal={6}
                  asterisked
                  required
                />
                <Button
                  appearance="text"
                  className={style.action}
                  type="button"
                  onClick={() => methods.setValue('price', baseDataInfo?.FScckj ?? '')}
                >
                  带入
                </Button>
              </div>
              <div className={classNames(style.staticItem, style.itemMargin)}>
                <span className={style.label}>市场参考价</span>
                <span className={style.value}>{baseDataInfo?.FScckj ? baseDataInfo?.FScckj : '-'}</span>
                <span className={style.unit}>
                  {formData.quote?.toUpperCase()}/{formData.base?.toUpperCase()}
                </span>
              </div>
            </div>
            <div className={classNames(style.row, style.rowMargin)}>
              <div className={classNames(style.input, style.itemMargin)}>
                <FormNumberInput
                  name="amount"
                  label="数量"
                  hint={amountInputHint}
                  decimal={6}
                  asterisked
                  required
                />
                <Button
                  appearance="text"
                  className={style.action}
                  type="button"
                  onClick={() => methods.setValue('amount', bnFixed(balance ?? ''))}
                >
                  最大
                </Button>
              </div>
              <div className={classNames(style.staticItem, style.itemMargin)}>
                <span className={style.label}>我将收到</span>
                <span className={style.value}>
                  {formData.price && formData.amount
                    ? bnFormat(bn(formData.price).times(formData.amount))
                    : '-'}
                </span>
                <span className={style.unit}>{formData.quote?.toUpperCase()}</span>
              </div>
            </div>
            <div className={classNames(style.row, style.rowMargin)}>
              <div className={classNames(style.input, style.itemMargin)}>
                <FormNumberInput
                  name="minTotal"
                  label="最小单笔限额"
                  // hint={t('trading.desc.minLimit', {
                  //   default: minOrderTotal ? bnFormat(minOrderTotal) : '-',
                  //   currency: formData.quote?.toUpperCase(),
                  // })}
                  hint={"最低收款金额: " + minOrderTotal + formData.quote?.toUpperCase()}
                  decimal={fiatDecimal}
                  asterisked
                  required
                />
                <span className={style.unit}>{formData.quote?.toUpperCase()}</span>
              </div>
              <div className={classNames(style.input, style.itemMargin)}>
                <FormNumberInput
                  name="maxTotal"
                  label="最大单笔限额"
                  // hint={t('trading.desc.maxLimit', {
                  //   default: maxOrderTotal ? bnFormat(maxOrderTotal) : '-',
                  //   currency: formData.quote?.toUpperCase(),
                  // })}
                  hint={"单笔收款限额: " + maxOrderTotal + formData.quote?.toUpperCase()}
                  decimal={fiatDecimal}
                  asterisked
                  required
                />
                <Button
                  appearance="text"
                  className={style.action}
                  type="button"
                  onClick={() =>
                    methods.setValue(
                      'maxTotal',
                      bn(methods.getValues('amount'))
                        .times(methods.getValues('price'))
                        .toFixed(fiatDecimal ?? 0, 3),
                    )
                  }
                >
                  最大
                </Button>
                <span className={style.unit}>{formData.quote?.toUpperCase()}</span>
              </div>
            </div>
            {/* <div className={classNames(style.row, style.rowMargin)}>
              <div className={classNames(style.input, style.itemMargin)}>
                <FormDatetimePicker
                  name="suspendedAt"
                  label="自动下架时间"
                  defaultValue={
                    stateTradingForm?.suspendedAt
                      ? new Date(stateTradingForm?.suspendedAt)
                      : undefined
                  }
                />
                <Button
                  appearance="text"
                  className={style.action}
                  type="button"
                  onClick={() => methods.setValue('suspendedAt', '')}
                >
                  {t('trading.act.clear')}
                </Button>
              </div>
            </div> */}
            <Alert severity={Severity.Clear} className={style.margin30}>
              若买家在6小时内未完成订单，管理员将介入处理
            </Alert>
          </div>
          <div className={classNames(style.subHeading, style.margin30)}>
            我的收款方式
          </div>
          {bankAccount !== undefined && bankAccount.length > 0 ? (
            <PaymentMethodsList
              name="bankAccountId"
              bankArray={bankAccount}
              defaultSelected={stateTradingForm?.bankAccountId}
            />
          ) : (
            <Alert severity={Severity.Warning} className={style.noPaymentAlert}>
              请先至 <Button key={0} appearance="text" onClick={() => navigate(Page.Account)} >账号</Button>
              页面新增收款方式
            </Alert>
          )}
          <div className={style.previewButton}>
            <Button
              size="large"
              type="submit"
              disabled={
                bankAccountId === undefined || Object.keys(methods.formState.errors).length !== 0
              }
            >
              预览
            </Button>
          </div>
        </Form>
      )}
    </div>
  );
};

export default Trading;


